package org.activequant.data.retrieval.ib;

import java.util.ArrayList;

import org.activequant.core.domainmodel.InstrumentSpecification;
import org.activequant.core.domainmodel.marketscanner.InstrumentSpecificationDetails;
import org.activequant.util.ib.IBTwsConnection;
import org.activequant.util.pattern.events.IEventListener;
import org.apache.log4j.Logger;

public class IBContractDetailsSource {
	/**
	 * private final IBTwsConnection connection;
	 */
	private final IBTwsConnection connection; 
	
	protected final static Logger log = Logger.getLogger(IBContractDetailsSource.class);
	/**
	 * constructs an IBContractDetailsSource using the given connection(IBTwsConnection)
	 * to set its associated connection(IBTwsConnection).
	 * @param connection
	 */
	public IBContractDetailsSource(IBTwsConnection connection){
		this.connection = connection;
	}
	
	private class ContractDetailsCallback {
		/**
		 * private final InstrumentSpecification spec;
		 */
		private final InstrumentSpecification spec;
		/**
		 * constructs a ContractDetailsCallback using the given s(InstrumentSpecification) to set its associated spec(InstrumentSpecification)
		 * @param s
		 */
		ContractDetailsCallback(InstrumentSpecification s) {
			spec = s;
		}
		/**
		 * private final IEventListener&lt;Quote&gt; listener = new IEventListener&lt;Quote&gt;() {...}<br/>
		 * A listener that re-fires any event(Quote)
		 */
		private final IEventListener<ArrayList<InstrumentSpecificationDetails>> listener = new IEventListener<ArrayList<InstrumentSpecificationDetails>>() {
			public void eventFired(ArrayList<InstrumentSpecificationDetails> event) {
				for(InstrumentSpecificationDetails details:event){
					log.info("got "+details.getInstrumentSpecification().getSymbol().toString());
				}
				
			}
		};

		protected void sendRequest(IEventListener<ArrayList<InstrumentSpecificationDetails>> otherListener) {
			connection.requestInstrumentSpecificationDetails(otherListener, spec);
		}
		
		protected void sendRequest() {
			connection.requestInstrumentSpecificationDetails(listener, spec);
		}

	}
	
	public void requestInstrumentSpecificationDetails(InstrumentSpecification spec) {
		ContractDetailsCallback cb= new ContractDetailsCallback(spec);
		cb.sendRequest();
	}
	
	public void requestInstrumentSpecificationDetails(InstrumentSpecification spec, IEventListener<ArrayList<InstrumentSpecificationDetails>> listener) {
		ContractDetailsCallback cb= new ContractDetailsCallback(spec);
		cb.sendRequest(listener);
	}
}
